import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/health_news_provider.dart';
import '../services/url_service.dart';

class HealthNewsPage extends StatefulWidget {
  const HealthNewsPage({super.key});

  @override
  State<HealthNewsPage> createState() => _HealthNewsPageState();
}

class _HealthNewsPageState extends State<HealthNewsPage> {
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 延迟初始化，避免在build期间调用setState
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<HealthNewsProvider>(context, listen: false).loadInitialNews();
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<HealthNewsProvider>(context);

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: _searchController,
                      decoration: const InputDecoration(
                        hintText: '搜索健康资讯',
                        prefixIcon: Icon(Icons.search),
                        border: OutlineInputBorder(),
                      ),
                      onSubmitted: (_) =>
                          provider.searchNews(_searchController.text),
                    ),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () =>
                        provider.searchNews(_searchController.text),
                    child: const Text('搜索'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  if (provider.totalResults > 0)
                    Text(
                      '共 ${provider.totalResults} 条结果，当前第 ${provider.currentPage} 页',
                      style: const TextStyle(
                        fontSize: 12,
                        color: Colors.grey,
                      ),
                    )
                  else
                    const SizedBox(),
                  Row(
                    children: [
                      const Text('随机模式:'),
                      Switch(
                        value: provider.isRandomMode,
                        onChanged: (_) => provider.toggleRandomMode(),
                        activeColor: Colors.green,
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
        Expanded(
          child: provider.isLoading && provider.newsList.isEmpty
              ? const Center(child: CircularProgressIndicator())
              : provider.newsList.isEmpty
                  ? Center(
                      child: provider.errorMessage.isNotEmpty
                          ? Text(provider.errorMessage)
                          : const Text('没有找到相关资讯'),
                    )
                  : RefreshIndicator(
                      onRefresh: () => provider.refreshNews(),
                      child: ListView.builder(
                        itemCount: provider.newsList.length + 1,
                        itemBuilder: (context, index) {
                          if (index == provider.newsList.length) {
                            return Padding(
                              padding:
                                  const EdgeInsets.symmetric(vertical: 16.0),
                              child: Center(
                                child: provider.isLoading
                                    ? const CircularProgressIndicator()
                                    : provider.hasMoreResults
                                        ? TextButton(
                                            onPressed: () =>
                                                provider.loadMoreNews(),
                                            child: const Text('加载更多'),
                                          )
                                        : const Text('已经到底了',
                                            style:
                                                TextStyle(color: Colors.grey)),
                              ),
                            );
                          }

                          final news = provider.newsList[index];
                          return Card(
                            margin: const EdgeInsets.all(8.0),
                            elevation: 2,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: ListTile(
                              contentPadding: const EdgeInsets.all(12.0),
                              leading: (news.picUrl.isNotEmpty)
                                  ? ClipRRect(
                                      borderRadius: BorderRadius.circular(8.0),
                                      child: Image.network(
                                        news.picUrl,
                                        width: 80,
                                        height: 80,
                                        fit: BoxFit.cover,
                                        errorBuilder: (_, __, ___) =>
                                            const Icon(
                                                Icons.image_not_supported,
                                                size: 80),
                                      ),
                                    )
                                  : null,
                              title: Text(
                                news.title,
                                style: const TextStyle(
                                    fontWeight: FontWeight.bold),
                              ),
                              subtitle: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  const SizedBox(height: 4),
                                  Text(news.description),
                                  const SizedBox(height: 4),
                                  Row(
                                    children: [
                                      Text(
                                        news.source,
                                        style:
                                            const TextStyle(color: Colors.grey),
                                      ),
                                      const Spacer(),
                                      Text(
                                        news.ctime,
                                        style:
                                            const TextStyle(color: Colors.grey),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                              onTap: () async {
                                if (news.url.isNotEmpty) {
                                  try {
                                    await UrlService.openUrl(news.url);
                                  } catch (e) {
                                    if (context.mounted) {
                                      ScaffoldMessenger.of(context)
                                          .showSnackBar(
                                        SnackBar(
                                            content:
                                                Text('无法打开链接: ${news.url}')),
                                      );
                                    }
                                  }
                                } else {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(content: Text('链接不可用')),
                                  );
                                }
                              },
                            ),
                          );
                        },
                      ),
                    ),
        ),
      ],
    );
  }
}
